//
//  JComposeVC.swift
//  JMicroBlog
//
//  Created by Jason on 28/5/15.
//  Copyright (c) 2015 Shepherd. All rights reserved.
//

import UIKit
import SVProgressHUD
class JComposeVC: UIViewController,UITextViewDelegate {
    // 自定义键盘控制器
    lazy var keyboardVC : JEmotionKeyboardVC = {
        weak var weakSelf = self
        return JEmotionKeyboardVC(selectedEmoticons: { (emoticons) -> () in
            //            weakSelf!.insertEmoticons(emoticons)
            weakSelf!.contentText.insertEmoticons(emoticons)
        })
    }()
    // 发布微博的内容
    @IBOutlet weak var contentText: JEmoticonsTextView!
    // toolbar底部约束
    @IBOutlet weak var bottomContraint: NSLayoutConstraint!
    // 发布微博上面显示的用户名
    @IBOutlet weak var accountLabel: UILabel!
    // 是否将要显示键盘
    var willHiddenKeyboard = false
    // 照片选择控制器
    var pictureSelector : JPictureSelectorCollectionVC?
    // 占位提示
    lazy var placeHolder:UILabel = {
        let l = UILabel(frame: CGRectMake(5, 8, 0, 0))
        l.text = "分享新鲜事..."
        l.font = UIFont.systemFontOfSize(18)
        l.textColor = UIColor.lightGrayColor()
        l.sizeToFit()
        return l
    }()
    // 发布按钮
    @IBOutlet weak var submit: UIBarButtonItem!
    private let maxContentLength = 140
    @IBOutlet weak var pictureViewHeightContraint: NSLayoutConstraint!
    @IBAction func closeBtnClick(sender: UIBarButtonItem) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置UI storyboard能自动添加子控制器
        setUI()
        // 调用注册通知方法
        registerNotification()
        // 成为代理对象
        contentText.delegate = self
    }
    
    // 设置UI的方法
    private func setUI() {
        // 添加键盘子控制器
        addChildViewController(keyboardVC)
        for vc in childViewControllers {
            if vc is JPictureSelectorCollectionVC {
                // 判断vc的原因,是为了以后的便于拓展
                pictureSelector = vc as? JPictureSelectorCollectionVC
                break
                
            }
        }
        accountLabel.text = sharedUserInfo?.name
        // 代码方式设置textView的垂直滚动
        contentText.alwaysBounceVertical = true
        // 将占位提示加入到view中
        contentText.addSubview(placeHolder)
        // 设置照片容器视图的高度
        pictureViewHeightContraint.constant = 0
    }
    // 可以阻止copy,和文字输入的方法,但是无法阻止联想输入的方式输入
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        // 判断回车 蛮重要的
        if (text == "\n"){
            JLog.i("回车")
        }
        if (textView.text as NSString).length + (text as NSString).length > 10 {
            return false
        }
        return true
    }
    // 在微博应用最后还要判断再次才好
    func textViewDidChange(textView: UITextView) {
        placeHolder.hidden = textView.hasText()
        // 允许发送按钮
        submit.enabled = textView.hasText()
        
        var text = contentText.fullText() as NSString
        if text.length > maxContentLength {
            text = text.substringToIndex(maxContentLength)
            contentText.text = text as String
        }
    }
    // 注册键盘通知方法
    private func registerNotification() {
        // 注册键盘位置改变状态(包括弹出与收回)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameChange:", name: UIKeyboardDidChangeFrameNotification, object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    // 响应键盘位置改变的方法
    func keyboardFrameChange(noti:NSNotification) {
        // 得到动画时长
        let during = noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        // 得到底部约束需要调整的偏移量
        var offsetY = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().size.height
        
        offsetY *= willHiddenKeyboard ? 0 : 1
        // 具体说切换键盘会跳跃 模拟器上看不出来?? 需要测试
        UIView.animateWithDuration(during, animations: {
            self.bottomContraint.constant = offsetY
            self.view.layoutIfNeeded()
        })
        willHiddenKeyboard = !willHiddenKeyboard
    }
    // 滚动textView调用scrollView的drag方法 拽scrollView结束后被调用
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        // 关闭键盘
        contentText.resignFirstResponder()
    }
    
    // 友好的关闭与显示键盘
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 如果没有图片,再激活键盘
        if pictureSelector?.pictureList.count <= 0 {
            contentText.becomeFirstResponder()
        }
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        contentText.resignFirstResponder()
    }
    
    // MARK: - Actions
    /** 发送微博 */
    @IBAction func sendWeibo(sender: UIBarButtonItem) {
        // 判断微博长度
        // 当微博内容的长度比最大长度大,提示用户,然后直接返回
        if count(contentText.fullText()) > maxContentLength {
            SVProgressHUD.showInfoWithStatus("输入内容过长", maskType: SVProgressHUDMaskType.Black)
            return
        }
        var urlString = ""
        // 这个真奇怪 等我第三次来的重新理思路的时候再改正吧 这个会导致带表情的微博无法发送出来的
        let params = ["access_token":sharedUserInfo?.access_token,"status":contentText.text]
        // 如果有图片数据
        if pictureSelector?.pictureList.count > 0 {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            // 参数字典
            let image = pictureSelector?.pictureList[0]
            let data = UIImagePNGRepresentation(image!)
            // key是保存在服务器的文件名
            // value是图片的二进制数据
            let dataList = ["abc":data]
            JNetworkTools.uploadPicture(urlString, fieldName: "pic", dataList: dataList, parameters:params)
            return
        }
        urlString = "https://api.weibo.com/2/statuses/update.json"
        JNetworkTools.responseJSON(.POST, URLString: urlString, params: params) { (JSON) in
            JLog.i("\(JSON)",false)
            // 关闭发布微博页面
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    }
    // 选择照片
    @IBAction func selectPicture() {
        // 照片容器的高度 = 屏幕高度的三分之一
        pictureViewHeightContraint.constant = UIScreen.mainScreen().bounds.height / 3
        
        // 关闭键盘
        contentText.resignFirstResponder()
    }
    
    /** 选择表情 */
    @IBAction func selectEmoticon() {
        // 因为目前有键盘 所以被强引用了 应该先被释放
        contentText.resignFirstResponder()
        // 设置表情输入视图
        contentText.inputView = contentText.inputView == nil ? keyboardVC.view : nil
        // 调出键盘
        contentText.becomeFirstResponder()
    }
    
}
